<template>
  <div>
    <!-- 标题 -->
    <div class="div-header">
      <h2 class="title">课时卡统计</h2>
    </div>

    <div class="container mb30">
      <!-- 查找和刷新按钮 -->
      <el-row justify="space-between" align="middle" class="search-refresh-row">
        <el-col :span="16">
          <el-row align="middle" class="search-bar">
            <el-col :span="20">
              <el-autocomplete v-model="search" :fetch-suggestions="querySearch" placeholder="卡号 / 学员ID / 卡名" clearable
                class="search-input" @select="handleSelect">
                <!-- 自定义下拉建议的展示内容 -->
                <template #default="{ item }">
                  <div class="autocomplete-item">
                    卡号: {{ item.cardId }} ｜ 学员ID: {{ item.studentId }} ｜ 卡名: {{ item.cardName }}
                  </div>
                </template>
              </el-autocomplete>
            </el-col>
            <el-col :span="4" class="search-button-col">
              <el-button type="primary" @click="handleSearch" class="search-button">
                查找
              </el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" class="refresh-button-col">
          <el-button-group>
            <el-button :icon="Refresh" type="success" @click="fetchCardStats" :loading="loading">
              刷新数据
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="pagedCards" style="width: 100%" border>
        <el-table-column label="卡号" prop="cardId" sortable />
        <el-table-column label="学员ID" prop="studentId" sortable />
        <el-table-column label="卡名称" prop="cardName" sortable />
        <el-table-column label="卡类型" :formatter="cardLevelFormatter" />
        <el-table-column label="总课次" prop="totalClasses" sortable />
        <el-table-column label="剩余课次" prop="remainingClasses" sortable />
        <el-table-column label="已用课次" :formatter="usedClasses" />
        <el-table-column label="价格(元)" prop="price" sortable />
        <el-table-column label="有效期" :formatter="formatDateRange" />
        <el-table-column label="提醒" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.isNotified" type="warning">提醒</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="prev, pager, next" :total="filteredCards.length" :page-size="pageSize"
          :current-page="currentPage" @current-change="handlePageChange" />
      </div>

      <!-- 图表 -->
      <!-- 图表部分 -->
      <el-row class="chart-container">
        <el-col :xs="24" :sm="24" :md="12" :lg="11">
          <div ref="classPieDom" class="chart-box"></div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="11">
          <div ref="moneyPieDom" class="chart-box"></div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const cardList = ref([])
const search = ref('')
const pageSize = ref(5)
const currentPage = ref(1)
const loading = ref(false)

const fetchCardStats = async () => {
  loading.value = true
  try {
    const { data } = await axios.get('http://localhost:8080/api/class-cards')
    cardList.value = Array.isArray(data) ? data : data.data
    calcStat()
    await nextTick()
    drawCharts()
    ElMessage.success('数据已刷新')
  } finally {
    loading.value = false
  }
}

function getCardLevel(cardName) {
  if (!cardName) return ''
  if (cardName.includes('初级')) return '初级卡'
  if (cardName.includes('中级')) return '中级卡'
  if (cardName.includes('高级')) return '高级卡'
  if (cardName.includes('进阶')) return '进阶卡'
  if (cardName.includes('体验')) return '体验卡'
  if (cardName.includes('特惠')) return '特惠卡'
  if (cardName.includes('基础')) return '基础卡'
  return '普通卡'
}

function cardLevelFormatter(row) {
  return getCardLevel(row.cardName)
}

const stat = reactive({
  totalClasses: 0,
  usedClasses: 0,
  remainingClasses: 0,
  totalPrice: 0,
  usedPrice: 0,
  remainingPrice: 0
})

function calcStat() {
  stat.totalClasses = 0
  stat.usedClasses = 0
  stat.remainingClasses = 0
  stat.totalPrice = 0
  stat.usedPrice = 0
  stat.remainingPrice = 0
  cardList.value.forEach(card => {
    stat.totalClasses += Number(card.totalClasses)
    stat.remainingClasses += Number(card.remainingClasses)
    stat.usedClasses += Number(card.totalClasses) - Number(card.remainingClasses)
    stat.totalPrice += Number(card.price)
    const used = Number(card.totalClasses) - Number(card.remainingClasses)
    const usedMoney = card.price * (used / card.totalClasses)
    stat.usedPrice += usedMoney
    stat.remainingPrice += card.price - usedMoney
  })
  stat.usedPrice = Number(stat.usedPrice.toFixed(2))
  stat.remainingPrice = Number(stat.remainingPrice.toFixed(2))
}

const filteredCards = computed(() => {
  if (!search.value) return cardList.value
  return cardList.value.filter(card =>
    card.cardId.includes(search.value) ||
    card.studentId.includes(search.value) ||
    card.cardName.includes(search.value)
  )
})

const pagedCards = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredCards.value.slice(start, start + pageSize.value)
})

function handlePageChange(page) {
  currentPage.value = page
}

// ✅ 新增的搜索函数
function handleSearch() {
  currentPage.value = 1
}

function usedClasses(row) {
  return Number(row.totalClasses) - Number(row.remainingClasses)
}

function formatDateRange(row) {
  return `${row.startDate} ~ ${row.expireDate}`
}

// 下拉联想：根据任意字段匹配整条卡片信息
function querySearch(queryString, cb) {
  const results = cardList.value.filter(card =>
    card.cardId.includes(queryString) ||
    card.studentId.includes(queryString) ||
    card.cardName.includes(queryString)
  )
  cb(results)
}

// 选中后只填入关键词字段（可自定义，这里填入卡号）
function handleSelect(item) {
  search.value = item.cardId // 或 `${item.cardId}-${item.cardName}` 也可以
}

const classPieDom = ref(null)
const moneyPieDom = ref(null)
let classPie = null
let moneyPie = null

function drawCharts() {
  if (classPieDom.value) {
    if (!classPie) classPie = echarts.init(classPieDom.value)
    classPie.setOption({
      title: {
        text: '课时统计',
        subtext: `总课时：${stat.totalClasses}`,
        left: 'center'
      },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      color: ['#fff1eb', '#ace0f9'],
      series: [
        {
          name: '课时',
          type: 'pie',
          radius: '60%',
          minAngle: 10, // 防止label被挤掉
          data: [
            {
              value: stat.usedClasses,
              name: '已用课时',
              itemStyle: { color: '#fff1eb' },
              emphasis: { itemStyle: { color: '#fff1eb' } }
            },
            {
              value: stat.remainingClasses,
              name: '剩余课时',
              itemStyle: { color: '#ace0f9' },
              emphasis: { itemStyle: { color: '#ace0f9' } }
            }
          ],
          label: {
            formatter: '{b}: {c} ({d}%)',
            fontSize: 15,
            lineHeight: 22,
            padding: [4, 0, 4, 0], 
            overflow: 'break'
          },
          labelLine: { length: 30, length2: 20 }
        }
      ]
    })
  }

  if (moneyPieDom.value) {
    if (!moneyPie) moneyPie = echarts.init(moneyPieDom.value)
    moneyPie.setOption({
      title: {
        text: '金额统计',
        subtext: `总金额：${stat.totalPrice}元`,
        left: 'center'
      },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      color: ['#fed6e3', '#a8edea'],
      series: [
        {
          name: '金额',
          type: 'pie',
          radius: '60%',
          minAngle: 10,
          data: [
            {
              value: stat.usedPrice,
              name: '已用金额',
              itemStyle: { color: '#fed6e3' },
              emphasis: { itemStyle: { color: '#fed6e3' } }
            },
            {
              value: stat.remainingPrice,
              name: '剩余金额',
              itemStyle: { color: '#a8edea' },
              emphasis: { itemStyle: { color: '#a8edea' } }
            }
          ],
          label: {
            formatter: '{b}: {c} ({d}%)',
            fontSize: 15,
            lineHeight: 22,
            padding: [4, 0, 4, 0], 
            overflow: 'break',
            show: true
          },
          labelLine: { length: 30, length2: 20 }
        }
      ]
    })
  }
}

onMounted(fetchCardStats)
onUnmounted(() => {
  if (classPie) classPie.dispose()
  if (moneyPie) moneyPie.dispose()
})
</script>


<style scoped lang="less">
.div-header {
  background-color: #fff;
  padding: 10px;
}

.title {
  font-size: 1.6rem;
  font-weight: bold;
  margin-left: 13px;
}

.search-refresh-row {
  margin-bottom: 20px;
}

.search-bar {
  width: 100%;
}

.search-input {
  width: 100%;
}

.search-button-col {
  padding-left: 10px;
}

.search-button {
  width: 100%;
}

.refresh-button-col {
  display: flex;
  justify-content: flex-end;
}

.chart-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.chart-box {
  height: 400px;
  margin-top: 50px;
  width: 100%; 
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.mb30 {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 30px;
}

.autocomplete-item {
  padding: 5px 8px;
  font-size: 14px;
  line-height: 1.5;
}
</style>
